import { transferLens, transferEachs } from "@/common/dicts/scoreToneTransfer";
// 和弦字符处理
const chooseSingleDeal = (str: string) => {
  // 空字符串直接返回
  if (str === "") {
    return "";
  }
  // 第一个字符
  const letter_first = str.substring(0, 1);
  // 后面的字符
  let letter_other = str.substring(1);
  letter_other = letter_other.replaceAll("maj", "");
  letter_other = letter_other.replace(/[^#mb]/g, '');
  return `${letter_first}${letter_other}`;
}

// 获取最终和弦
const getChord = (arr: any[], chords) => {
  let final_chord = null;
  // 带'/'查询
  const nameArr = arr.map(x => x.name).filter(x => !!x);
  const str1 = nameArr.length > 1 ? nameArr.join("/") : "";
  const idx1 = chords.findIndex(x => str1 === x.name);
  if (idx1 > -1) {
    final_chord = chords[idx1];
  }
  // 带'm'查询
  arr.forEach(x => {
    const idx2 = chords.findIndex(y => y.name === x.name + 'm');
    if (x.m && idx2 > -1) {
      !final_chord && (final_chord = chords[idx2]);
    }
  })
  // 单个查询
  arr.forEach(x => {
    const idx3 = chords.findIndex(y => y.name === x.name);
    if (idx3 > -1) {
      !final_chord && (final_chord = chords[idx3]);
    }
  })
  return final_chord;
}

export default (choose: string, score_tone: string, chords: any[]) => {
  // 获取曲谱和弦加减值
  const len = transferLens[score_tone];
  // 获取和弦组
  let choose_wait_arr: any = choose.split("/");
  // 和弦字符处理
  choose_wait_arr = choose_wait_arr.map(x => chooseSingleDeal(x));
  // 和弦组内容对象化
  choose_wait_arr = choose_wait_arr.map(x => {
    return {
      name: x.replace(/m/g, ''),
      m: x.indexOf('m') > -1,
    }
  })
  // 和弦组内容转化
  const choose_arr = choose_wait_arr.map(x => {
    return {
      name: transferEachs?.[x.name]?.[len.toString()],
      m: x.m,
    }
  })
  return getChord(choose_arr, chords);
}